var fs = require('fs');
const userCenter = require("./userCenter/index.js")
const Login = require("./userService.js")
const ListMenu = require("./utils.js")
const platformService = require("./platformService.js")
const member= require("./member.js")
const Mock = {
    ...userCenter,
    ...Login,
    ...ListMenu,
    ...platformService,
    ...member
}
console.log("模拟的数据：",Mock)





var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));

// parse application/json  
app.use(bodyParser.json())
//设置跨域访问  
app.all('*', function (req, res, next) {
    console.log(req.headers.origin)
    res.header("Access-Control-Allow-Origin", req.headers.origin);//直接把来源地址设置为允许的域名，也可以先写个数组，然后判断之后再赋值
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});

app.post('*', function (req, res) {
    console.log(req.params["0"])
    let result = Mock[req.params["0"]](req.body);
    console.log(result)
    console.log("post接受的的内容",req.body)
    res.json(result);
});
app.get('*', function (req, res) {
    if(req.originalUrl!="/favicon.ico"){
        let originalUrl=req.originalUrl;//.substring(1);//去除第一个”/“
    console.log(Mock,originalUrl)
     let result = Mock[originalUrl](req.query);
    console.log("GET,请求的连接:",req.originalUrl,"======================")
    console.log("响应内容:",result)
    res.json(result);
    }
   
});
app.listen(3006);
console.log('Listening on  http://localhost:3006');


const Match = `
export const Match=(url,isNoMock)=>{
    let tmp;
    if(process.env.NODE_ENV === 'production'||isNoMock){
        return url;
    }
    for (let [key, value] of Object.entries(Mock)) {
         if(key == url){
            
            tmp= "http://localhost:3006"+key;
            break;
         }
         else if(url=="user/listMenu"){
             //对左侧列表特殊处理
            tmp= "http://localhost:3006/user/listMenu";
            break;
         }
         else if(url=="user/login"){
            //对登录特殊处理
           tmp= "http://localhost:3006/user/login";
           break;
        }
      }
    return tmp?tmp:url;
};`;
//把function转换为字符串
let dataJSON = JSON.stringify(Mock, function (key, val) {
    if (typeof val === 'function') {
        return '';
    }
    return val;
});
var dataString = "const Mock=" + dataJSON + ";" + Match;
console.log(Mock)
console.log(dataJSON)
var w_data = Buffer.from(dataString);
//写入给前端使用的json对应的value是一个字符串function，我们只需要用到它的key
fs.writeFileSync(__dirname + '/indexForbrowser.js', w_data, function (err) {
    if (err) {
        console.error(err);
    } else {
        console.log('写入成功');
    }
});